package com.peaksport.framework.extend.schedule;

import com.peaksport.framework.extend.spring.PKApplicationContext;
import com.peaksport.framework.util.PKPublicUtils;
import com.peaksport.pkms.system.entity.ScheduleDefEntity;
import com.peaksport.pkms.system.entity.ScheduleInstEntity;
import com.peaksport.pkms.system.venum.ScheduleStatusEnum;

import lombok.Getter;
import lombok.Setter;

@Setter
@Getter
public abstract class PKCornScheduleRunnable implements Runnable {
	
	private PKScheduleService service;
	private ScheduleDefEntity scheduleDefEntity;

	@Override
	public void run() {
		ScheduleInstEntity scheduleInstEntity = null;
		try {
			String curMicroService = PKApplicationContext.getMicroService();
			String runInMicroService = scheduleDefEntity.getMicroService();
			//判断是否有指定特定运行服务
			if (runInMicroService != null && !runInMicroService.equals(curMicroService)) return;
			//校验当前事务是否在运行中,如果运行中直接退出
			boolean isRunning = service.isRunning(scheduleDefEntity);
			if (isRunning) return;
			//设置事务启动时间、执行运行状态
			scheduleInstEntity = service.addNewScheduleInst(scheduleDefEntity);
			//执行事务reallyRun..
			doRun();
			//设置执行完成状态
			scheduleInstEntity.setStatus(ScheduleStatusEnum.COMPLETE);
		} catch (Exception exc) {
			//设置执行异常
			scheduleInstEntity.setStatus(ScheduleStatusEnum.FAILURE);
			scheduleInstEntity.setExpLog(PKPublicUtils.getStackTrace(exc));
		} finally {
			//设置执行
			scheduleInstEntity.setFinishTime(service.getCurrentTime());
			service.updateScheduleInst(scheduleInstEntity);
		}
		
	}
	
	public abstract void doRun() throws Exception;
}